using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;
using Windows.UI.Core;
using BlogApp.Data.Models;
using BlogApp.Data.Service;
using BlogApp.WP8.Utils;
using GalaSoft.MvvmLight.Command;

namespace BlogApp.WP8.ViewModel
{
    public class MainViewModel : DataViewModel
    {
        private Dispatcher _dispatcher;

        private CategoryResult _categoryResult;
        public CategoryResult CategoryResult
        {
            get { return _categoryResult; }
            set { _categoryResult = value; RaisePropertyChanged("CategoryResult"); }
        }

        private bool _areOfflinePosts;

        public bool AreOfflinePosts
        {
            get { return _areOfflinePosts; }
            set { _areOfflinePosts = value; RaisePropertyChanged("AreOfflinePosts"); }
        }


        private PostResult _recentPostst;
        public PostResult RecentPostst
        {
            get { return _recentPostst; }
            set { _recentPostst = value; RaisePropertyChanged("RecentPostst"); }
        }

        private bool _isOffline;
        public bool IsOffline
        {
            get { return _isOffline; }
            set { _isOffline = value; RaisePropertyChanged("IsOffline"); }
        }

        private int _totalPageCount = 0;
        private List<Post> _offlinePosts;

        public List<Post> OfflinePosts
        {
            get { return _offlinePosts; }
            set { _offlinePosts = value; RaisePropertyChanged("OfflinePosts"); }
        }

        public RelayCommand LoadOfflinePosts { get; private set; }

        public RelayCommand LoadDataCommand;
        public RelayCommand LoadMoreItems { get; private set; }
        public NavigateCommand NavigateCommand { get; private set; }


        public MainViewModel()
        {
            _dispatcher = App.RootFrame.Dispatcher;

            NavigateCommand = new NavigateCommand();
            LoadDataCommand = new RelayCommand(loadData);
            LoadMoreItems = new RelayCommand(loadMoreItems);
            LoadOfflinePosts = new RelayCommand(loadOfflinePosts);

            // Get Blog-Url and Init Dataservice
            var blogUrl = App.Current.Resources["BlogUrl"].ToString();
            DataService.Instance.InitDataservice(blogUrl);

            DataService.Instance.NetworkStatusChanged += OnNetworkStatusChanged;

        }

        private async void OnNetworkStatusChanged(object sender, NetworStatusEventArgs args)
        {
            if (!args.IsOffline)
            {

                Deployment.Current.Dispatcher.BeginInvoke(() =>
                                                          {
                                                              loadData();
                                                              IsOffline = false;
                                                          });

            }
            else
            {
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                                                          {
                                                              IsOffline = true;
                                                          });

            }
        }

        int _currentPageIndex = 2;
        private async void loadMoreItems()
        {
            if (!DataService.Instance.IsOffline)
            {
                IsLoading = true;
                try
                {
                    if (_currentPageIndex < _totalPageCount)
                    {
                        var moreItems = await DataService.Instance.GetRecentPostsAsync(_currentPageIndex);

                        if (moreItems != null)
                            _recentPostst.Posts.AddRange(moreItems.Posts);
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                }

                IsLoading = false;
            }
        }

        private async void loadOfflinePosts()
        {
            OfflinePosts = await DataService.Instance.LoadOfflinePosts();
            AreOfflinePosts = OfflinePosts.Any();
        }

        private async void loadData()
        {

            IsLoading = true;
            await loadCategories();
            await loadRecentPostst();
            IsLoading = false;

            NavigateCommand.Execute("/View/MainPage.xaml");
            NavigateCommand.ClearBackStack();
        }

        private async Task loadRecentPostst()
        {
            try
            {
                var recentPostResult = await DataService.Instance.GetRecentPostsAsync(1, 10);
                if (recentPostResult != null)
                {
                    _totalPageCount = recentPostResult.Pages;
                    RecentPostst = recentPostResult;
                }
            }
            catch (Exception)
            {

            }
        }

        private async Task loadCategories()
        {
            try
            {

                var catResult = await DataService.Instance.GetCategoriesAsync();

                var offlinePosts = await DataService.Instance.LoadOfflinePosts();
                if (offlinePosts.Any())
                {
                    OfflinePosts = offlinePosts;
                    AreOfflinePosts = true;
                    // when offline, catResult is null
                    if (catResult == null)
                    {
                        catResult = new CategoryResult();
                        catResult.Categories = new List<Category>();
                    }
                }

                CategoryResult = catResult;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }


        #region Convert Youtube-Links to embedded vidos
        //// get all links
        //IEnumerable<HtmlNode> linkCollection = document.DocumentNode.Descendants("a");
        //// filter links by href-attribute, only starting with "youtube"
        //linkCollection = linkCollection.Where(x => x.Attributes.FirstOrDefault(y => y.Name == "href").Value.StartsWith("http://youtu")).ToList();
        //// filter duplicate videos
        //linkCollection = linkCollection.DistinctBy(v => v.Attributes.FirstOrDefault(w => w.Name == "href").Value);

        //foreach (var htmlNode in linkCollection)
        //{
        //    var videoId = htmlNode.Attributes.FirstOrDefault(z => z.Name == "href").Value;
        //    videoId = videoId.Substring(videoId.LastIndexOf("/"));

        //    var newVideoNode = string.Format(@"<iframe width=""800"" height=""480"" src=""http://www.youtube.com/embed{0}""?rel=0"" frameborder=""0"" allowfullscreen></iframe>", videoId);
        //    var node = HtmlNode.CreateNode(newVideoNode);

        //    document.DocumentNode.AppendChild(node);
        //}

        #endregion

    }
}